//
//  SurGroupAddViewController.m
//  wAudioShare
//
//  Created by 赵帅 on 14-1-11.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "SurGroupOperationViewController.h"
#import "SurGroupObject.h"

@interface SurGroupOperationViewController ()
<serviceAddAudioToGroupDelegate>
{
    NSMutableArray * selectedArray;
}

@property (assign) IBOutlet UITextField * groupNameField;
@property (assign) IBOutlet UITableView * tableView;

@end

@implementation SurGroupOperationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    selectedArray = [[NSMutableArray alloc] init];
    
    if([_groupObj.groupName length] != 0)
    {
        _groupNameField.text = _groupObj.groupName;
        _groupNameField.enabled = NO;
    }
    
    [self prepareUI];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return @"Surrounder";
}


#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"请选择要添加的设备";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self makeLocalDevices] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    else
    {
        for(UIView * subview in [cell.contentView subviews])
        {
            [subview removeFromSuperview];
        }
    }
    
    // Configure the cell.
    NSArray * arr = [self makeLocalDevices];
    cell.textLabel.text = arr[indexPath.row][@"name"];
    if([self isDeviceSelected:arr[indexPath.row]])
    {
        UIImageView * rightImage = nil;
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chosen.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-45, 20, 20, 20);
        [cell.contentView addSubview:rightImage];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    NSDictionary * dic = [self makeLocalDevices][indexPath.row];
    
    BOOL isExsit = NO;
    NSDictionary * tempDic = nil;
    for(tempDic in selectedArray)
    {
        if(tempDic == dic)
        {
            isExsit = YES;
            break;
        }
    }
    
    if(isExsit == YES)
    {
        [selectedArray removeObject:dic];
    }
    else
    {
        [selectedArray addObject:dic];
    }
    
    [self.tableView reloadData];
}

#pragma mark - private methods
-(void)prepareUI
{
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"normalbutton_normal"]
                          forState:UIControlStateNormal];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"normalbutton_press"]
                          forState:UIControlStateHighlighted];
    confirmButton.frame = CGRectMake(0, 0, 73, 38);
    
    UIBarButtonItem* rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:confirmButton];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

-(void)confirmButtonPressed:(id)sender
{
    NSString * note = nil;
    if([_groupNameField.text length] == 0)
    {
        note = @"请输入组名";
    }
    else if([selectedArray count] == 0)
    {
        note = @"请至少选择一个设备";
    }
    else if([_groupNameField.text length] >= 20)
    {
        note = @"组名应少于20个字符";
    }
    
    if(note != nil)
    {
        UIAlertView * av = [[UIAlertView alloc] initWithTitle:@"提示"
                                                       message:note
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [av show];
        
        return;
    }
    
    for(NSDictionary * dic in selectedArray)
    {
        [[GlobalService sharedInstance] addAudioToGroup:self baseURL:dic[@"ip"] groupName:_groupNameField.text];
    }
    
    [_delegate devicesAddToGroup:selectedArray];
    [self.navigationController popViewControllerAnimated:YES];
}

-(BOOL)isDeviceSelected:(NSDictionary *)dic
{
    for(NSDictionary * tempDic in selectedArray)
    {
        if(dic == tempDic) return YES;
    }
    return NO;
}

-(NSArray *)makeLocalDevices
{
    NSArray * tempArray = [_datasource getAllDevices];
    NSMutableArray * localArr = [NSMutableArray array];
    
    for(NSDictionary * localDic in tempArray)
    {
        BOOL isExsit = NO;
        for(NSString * str in _groupObj.audioGroup)
        {
            if([localDic[@"name"] isEqualToString:str])
            {
                isExsit = YES;
                break;
            }
        }
        
        if(isExsit == NO)
        {
            [localArr addObject:localDic];
        }
    }
    
    return localArr;
}

#pragma mark - textfield delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_groupNameField resignFirstResponder];
    return YES;
}

-(void)serviceAddAudioToGroupCallBack:(NSDictionary*)dicCallBack
{

}

@end
